﻿using Dora.Orm.SqlSugarCore.UnitOfWork;
using Dora.Services.AdminUser.Application.Base;
using Dora.Services.AdminUser.Dto.QueryDto;
using Dora.Services.AdminUser.Dto.ViewDto;
using Dora.Services.AdminUser.Entities;
using Dora.Services.AdminUser.IApplication;
using Dora.Services.AdminUser.Repository;
using Dora.Tools.Utility.Const;
using Surging.Core.Common;
using Surging.Core.CPlatform.Ioc;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Linq;
using Mapster;
using Dora.Services.AdminUser.Dto.SaveDto;
using Dora.Tools.Enums.Supplier;
using Dora.Tools.Enums.Product;
using Dora.Services.AdminUser.Repository.Repositorys;

namespace Dora.Services.AdminUser.Application
{
    /// <summary>
    /// 大社产品类型/目的地保险产品绑定服务接口
    /// </summary>
    [ModuleName(DoraModuleName.AdminUser)]
    public class OrgInsuranceSettingService: DoraServiceBase, IOrgInsuranceSettingService
    {
        private ISugarUnitOfWork _unitOfWork;
        private readonly OrgInsuranceSettingRepository _OrgInsuranceSettingRepository;
        private readonly OrgInsuranceSupplierRepository _repository;
        private readonly OrgInsuranceSupplierAreaRepository _areaRepository;
        private readonly OrganizationRepository _OrganizationRepository;
        public OrgInsuranceSettingService(ISugarUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
            _OrgInsuranceSettingRepository = new OrgInsuranceSettingRepository(unitOfWork);
            _repository = new OrgInsuranceSupplierRepository(unitOfWork);
            _areaRepository = new OrgInsuranceSupplierAreaRepository(unitOfWork);
            _OrganizationRepository = new OrganizationRepository(unitOfWork);
        }
        /// <summary>
        /// 批量新增及修改
        /// </summary>
        /// <param name="orgInsuranceSettingEntities"></param>
        /// <returns></returns>
        public async Task<bool> BatchSaveOrgInsuranceSettings(List<OrgInsuranceSettingEntity> orgInsuranceSettingEntities) 
        {
            return await _OrgInsuranceSettingRepository.BatchSaveOrgInsuranceSettings(orgInsuranceSettingEntities);
        }
        /// <summary>
        /// 分页获取数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ResultDto<PageDataList<OrgInsuranceSettingEntity>>> GetOrgInsuranceSettingPageList(OrgInsuranceSettingQueryDto input) 
        {
            var pageData = await _OrgInsuranceSettingRepository.GetOrgInsuranceSettingPageList(input);
            return ResultDto<PageDataList<OrgInsuranceSettingEntity>>.Success(pageData);
        }
        /// <summary>
        /// 获取所有数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ResultDto<List<OrgInsuranceSettingEntity>>> GetOrgInsuranceSettingByOrg(OrgInsuranceSettingQueryDto input)
        {
            var pageData = await _OrgInsuranceSettingRepository.GetOrgInsuranceSettingAll(input);
            return ResultDto<List<OrgInsuranceSettingEntity>>.Success(pageData);
        }

        public async Task<List<OrgInsuranceSettingViewDto>> GetOrgInsuranceSettingViewDtoByOrg(OrgInsuranceSettingQueryDto input)
        {
            var ListData = await _OrgInsuranceSettingRepository.GetOrgInsuranceSettingAll(input);
            List<OrgInsuranceSettingViewDto> OrgInsuranceSettingEntitys = new List<OrgInsuranceSettingViewDto>();
            if (ListData != null )
            {
                for (int i = 0; i < ListData.Count; i++)
                {
                    OrgInsuranceSettingViewDto OrgInsuranceSettingViewDto = ListData[i].Adapt<OrgInsuranceSettingViewDto>();

                    OrgInsuranceSettingViewDto.OrgInsuranceExcludes = new List<OrgInsuranceSupplierSaveDto>();

                    List<OrgInsuranceSupplierSaveDto> orgInsuranceSuppliers = await GetAllByOrgId(input.OrgId, OrgInsuranceSettingViewDto.BindType, OrgInsuranceSettingViewDto.BindId);

                    if (orgInsuranceSuppliers != null && orgInsuranceSuppliers.Count > 0)
                    {
                        OrgInsuranceSettingViewDto.OrgInsuranceExcludes.AddRange(orgInsuranceSuppliers);
                    }
                    if (input.ParentOrgId > 0)
                    {

                        List<OrgInsuranceSupplierSaveDto> orgInsuranceSuppliers1 = await GetAllByOrgId(input.ParentOrgId, OrgInsuranceSettingViewDto.BindType, OrgInsuranceSettingViewDto.BindId);

                        if (orgInsuranceSuppliers1 != null && orgInsuranceSuppliers1.Count > 0)
                        {
                            OrgInsuranceSettingViewDto.OrgInsuranceExcludes.AddRange(orgInsuranceSuppliers1);
                        }
                    }
                    OrgInsuranceSettingEntitys.Add(OrgInsuranceSettingViewDto);
                }
            }
            return OrgInsuranceSettingEntitys;
        }
        public async Task<List<OrgInsuranceSupplierSaveDto>> GetAllByOrgId(int orgId, int BindType, int BindId)
        {

            List<OrgInsuranceSupplierSaveDto> views = new List<OrgInsuranceSupplierSaveDto>();
            List<OrgInsuranceSupplierEntity> supplierEntities = await _repository.GetAllByOrgId(orgId, BindType, BindId);


            for (int i = 0; supplierEntities != null && i < supplierEntities.Count; i++)
            {
                OrgInsuranceSupplierSaveDto supplierSaveDto = supplierEntities[i].Adapt<OrgInsuranceSupplierSaveDto>();
                List<OrgInsuranceSupplierAreaEntity> areaEntitys = await _areaRepository.GetAllByOrgId(orgId, supplierSaveDto.SettingId, supplierSaveDto.Id);
                supplierSaveDto.OrgInsuranceSupplierAreas = areaEntitys.Adapt<List<OrgInsuranceSupplierAreaSaveDto>>();
                views.Add(supplierSaveDto);
            }
            return views;
        }

        /// <summary>
        /// 逻辑删除或恢复
        /// </summary>
        /// <param name="orgInsuranceSettingEntities"></param>
        /// <param name="isDelete"></param>
        /// <returns></returns>
        public async Task<int> UpZOrgSeting(List<OrgInsuranceSettingEntity> orgInsuranceSettingEntities, Boolean isDelete)
        {
            return await _OrgInsuranceSettingRepository.UpZOrgSeting(orgInsuranceSettingEntities,isDelete);
        }
        /// <summary>
        /// 彻底删除
        /// </summary>
        /// <param name="orgInsuranceSettingEntities"></param>
        /// <returns></returns>
        public async Task<int> ClearZOrgSeting(List<OrgInsuranceSettingEntity> orgInsuranceSettingEntities)
        {
            for (int i = 0; i < orgInsuranceSettingEntities.Count; i++)
            {
                await _repository.DeleteAsync(t => t.SettingId == orgInsuranceSettingEntities[i].Id);
                await _areaRepository.DeleteAsync(t => t.SettingId == orgInsuranceSettingEntities[i].Id);
            }
            
            return await _OrgInsuranceSettingRepository.ClearZOrgSeting(orgInsuranceSettingEntities);
        }
        /// <summary>
        /// 批量获取默认集合
        /// </summary>
        /// <param name="orgInsuranceDefaultEntities"></param>
        /// <returns></returns>
        public async Task<List<OrgInsuranceDefaultEntity>> GetOrgInsuranceDefaultEntities(List<OrgInsuranceDefaultEntity> orgInsuranceDefaultEntities)
        {
            for (int i = 0; orgInsuranceDefaultEntities!=null && i < orgInsuranceDefaultEntities.Count; i++)
            {
                OrgInsuranceSettingEntity orgInsuranceSettingEntity = null;
                //if (orgInsuranceDefaultEntities[i].ParentOrgId > 0)
                //{
                //    var ListData = await _OrgInsuranceSettingRepository.GetOrgInsuranceSettingAll(new OrgInsuranceSettingQueryDto() { BindId = orgInsuranceDefaultEntities[i].BindId, BindType = orgInsuranceDefaultEntities[i].BindType, OrgId = orgInsuranceDefaultEntities[i].ParentOrgId });
                //    if (ListData == null || ListData.Count < 1)
                //    {
                //        continue;
                //    }
                //    else
                //    {
                //        orgInsuranceSettingEntity = ListData[0];
                //    }
                //}
                //else
                //{
                //    var ListData = await _OrgInsuranceSettingRepository.GetOrgInsuranceSettingAll(new OrgInsuranceSettingQueryDto() { BindId = orgInsuranceDefaultEntities[i].BindId, BindType = orgInsuranceDefaultEntities[i].BindType, OrgId = orgInsuranceDefaultEntities[i].OrgId });
                //    if (ListData == null || ListData.Count < 1)
                //    {
                //        continue;
                //    }
                //    else
                //    {
                //        orgInsuranceSettingEntity = ListData[0];
                //    }
                //}

                var ListData = await _OrgInsuranceSettingRepository.GetOrgInsuranceSettingAll(new OrgInsuranceSettingQueryDto() { BindId = orgInsuranceDefaultEntities[i].BindId, BindType = orgInsuranceDefaultEntities[i].BindType, OrgId = orgInsuranceDefaultEntities[i].ParentOrgId>0? orgInsuranceDefaultEntities[i].ParentOrgId: orgInsuranceDefaultEntities[i].OrgId });
                if (ListData == null || ListData.Count < 1)
                {
                    continue;
                }
                else
                {
                    orgInsuranceSettingEntity = ListData[0];
                }


                if (orgInsuranceSettingEntity==null)
                {
                    continue;
                }

                List<OrgInsuranceSupplierEntity> supplierEntities = await _repository.GetAllByOrgId(orgInsuranceDefaultEntities[i].ParentOrgId > 0 ? orgInsuranceDefaultEntities[i].ParentOrgId : orgInsuranceDefaultEntities[i].OrgId, orgInsuranceDefaultEntities[i].BindType, orgInsuranceDefaultEntities[i].BindId, orgInsuranceDefaultEntities[i].SupplierId);

                if (supplierEntities != null && supplierEntities.Count > 0)
                {
                    if (supplierEntities[0].IsExcludeSupplier)
                    {
                        continue;
                    }
                    else
                    {
                        var areaList = await _areaRepository.GetAllByOrgId(supplierEntities[0].OrgId, supplierEntities[0].SettingId, supplierEntities[0].Id, orgInsuranceDefaultEntities[i].AreaId);
                        if (areaList != null && areaList.Count > 0)
                        {
                            continue;
                        }
                    }
                }


                //List<OrgInsuranceSupplierEntity> supplierEntities = await _repository.GetAllByOrgId(orgInsuranceDefaultEntities[i].OrgId, orgInsuranceDefaultEntities[i].BindType, orgInsuranceDefaultEntities[i].BindId, orgInsuranceDefaultEntities[i].SupplierId);

                //if (supplierEntities!=null&& supplierEntities.Count>0)
                //{
                //    if (supplierEntities[0].IsExcludeSupplier)
                //    {
                //        continue;
                //    }
                //    else
                //    {
                //       var areaList = await _areaRepository.GetAllByOrgId(supplierEntities[0].OrgId, supplierEntities[0].SettingId, supplierEntities[0].Id, orgInsuranceDefaultEntities[i].AreaId);
                //        if (areaList!=null&&areaList.Count>0)
                //        {
                //            continue;
                //        }
                //    }
                //}
                //List<OrgInsuranceSupplierEntity> supplierPEntities = await _repository.GetAllByOrgId(orgInsuranceDefaultEntities[i].ParentOrgId, orgInsuranceDefaultEntities[i].BindType, orgInsuranceDefaultEntities[i].BindId, orgInsuranceDefaultEntities[i].SupplierId);
                //if (supplierPEntities != null && supplierPEntities.Count > 0)
                //{
                //    if (supplierPEntities[0].IsExcludeSupplier)
                //    {
                //        continue;
                //    }
                //    else
                //    {
                //        var areaList = await _areaRepository.GetAllByOrgId(supplierPEntities[0].OrgId, supplierPEntities[0].SettingId, supplierPEntities[0].Id, orgInsuranceDefaultEntities[i].AreaId);
                //        if (areaList != null && areaList.Count > 0)
                //        {
                //            continue;
                //        }
                //    }
                //}
                orgInsuranceDefaultEntities[i].InsuranceOrgProId = orgInsuranceSettingEntity.InsuranceOrgProId;
                orgInsuranceDefaultEntities[i].InsuranceOrgProName = orgInsuranceSettingEntity.InsuranceOrgProName;
            }
            return orgInsuranceDefaultEntities;
        }
        /// <summary>
        /// 根据外键获取此供应商排除的区域
        /// </summary>
        /// <param name="ExcludeSupplierId"></param>
        /// <returns></returns>
        public async Task<List<OrgInsuranceSupplierAreaEntity>> GetByExcludeSupplierId(int ExcludeSupplierId) 
        {
            return await _areaRepository.GetAllByGetByExcludeSupplierId(ExcludeSupplierId);
        }
        /// <summary>
        /// 组团社解约供应商或其签约区域
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ResultDto> DelSupplierAreas(RescissionSupplierUpdateDto input)
        {
            try
            {
                OrganizationEntity organizationEntity = await _OrganizationRepository.GetOrganizationInfoById(input.OrgId);

                List<OrgInsuranceSupplierAreaEntity> AreaDelEntity = new List<OrgInsuranceSupplierAreaEntity>();
                List<OrgInsuranceSupplierEntity> SupplierDelEntity = new List<OrgInsuranceSupplierEntity>();

                List<OrgInsuranceSettingEntity> orgInsuranceSettingEntities = await _OrgInsuranceSettingRepository.GetOrgInsuranceSettingAllByLevePath(input.OrgId.ToString());


                if (organizationEntity.OrgLevel != 0)
                {
                    List<OrgInsuranceSettingEntity> orgInsuranceSettingEntitiesP = await _OrgInsuranceSettingRepository.GetOrgInsuranceSettingAllByLevePath(organizationEntity.ParentId.ToString());
                    if (orgInsuranceSettingEntitiesP != null && orgInsuranceSettingEntitiesP.Count > 0)
                    {
                        orgInsuranceSettingEntities.AddRange(orgInsuranceSettingEntitiesP);
                    }
                }

                if (input.IsAll)
                {
                    if (orgInsuranceSettingEntities != null && orgInsuranceSettingEntities.Count > 0)
                    {
                        for (int i = 0; i < orgInsuranceSettingEntities.Count; i++)
                        {
                            List<OrgInsuranceSupplierEntity> supplierEntities = await _repository.GetAllBySettingId(orgInsuranceSettingEntities[i].Id);

                            supplierEntities = supplierEntities.Where(t => t.SupplierId == input.SupplierId).ToList();

                            for (int j = 0; j < supplierEntities.Count; j++)
                            {
                                List<OrgInsuranceSupplierAreaEntity> orgInsuranceSupplierAreaEntities = await _areaRepository.GetAllByGetByExcludeSupplierId(supplierEntities[j].Id);

                                List<OrgInsuranceSupplierAreaEntity> orgInsuranceSupplierAreaEntities1 = orgInsuranceSupplierAreaEntities.Where(t => t.SourceOrgId == input.OrgId).ToList();

                                if (orgInsuranceSupplierAreaEntities.Count== orgInsuranceSupplierAreaEntities1.Count)
                                {
                                    SupplierDelEntity.Add(supplierEntities[j]);
                                }
                                AreaDelEntity.AddRange(orgInsuranceSupplierAreaEntities1);
                            }
                        }
                    }
                }
                else
                {
                    if (orgInsuranceSettingEntities != null && orgInsuranceSettingEntities.Count > 0)
                    {
                        if (input.ProductAreaIds!=null && input.ProductAreaIds.Count>0)
                        {
                            for (int w = 0; w < input.ProductAreaIds.Count; w++)
                            {
                                
                                int BindId = input.ProductAreaIds[w].CooperationScopeId;

                                if ((int)CooperationScopeType.SignleBusiness== BindId)
                                {
                                    BindId = -1;
                                }
                                else if((int)CooperationScopeType.Cruise == BindId)
                                {
                                    BindId = (int)ProductType.YouLun;
                                }
                                else if ((int)CooperationScopeType.Domestic == BindId)
                                {
                                    BindId = (int)ProductType.GuoNeiYou;
                                }
                                else if ((int)CooperationScopeType.GoAbroad == BindId)
                                {
                                    BindId = (int)ProductType.HaiChang;//33    
                                }
                                else if ((int)CooperationScopeType.TravelAround == BindId)
                                {
                                    BindId = (int)ProductType.ZhouBianYou;
                                }

                                List<OrgInsuranceSettingEntity> orgInsuranceSettings = orgInsuranceSettingEntities.Where(t => t.BindId == BindId && t.BindType == 1).ToList();

                                //出境游  包括  海长,海短
                                if (BindId == (int)ProductType.HaiChang)
                                {
                                    List<OrgInsuranceSettingEntity> orgInsuranceSettings1 = orgInsuranceSettingEntities.Where(t => t.BindId == (int)ProductType.HaiDuan && t.BindType == 1).ToList();
                                    if (orgInsuranceSettings1!=null && orgInsuranceSettings1.Count>0)
                                    {
                                        orgInsuranceSettings.AddRange(orgInsuranceSettings1);
                                    }
                                }

                                if (input.IsClearTW)
                                {
                                    orgInsuranceSettings.AddRange(orgInsuranceSettingEntities.Where(t => t.BindId == 46245 && t.BindType ==2).ToList());
                                }
                                for (int i = 0; i < orgInsuranceSettings.Count; i++)
                                {
                                    List<OrgInsuranceSupplierEntity> supplierEntities = await _repository.GetAllBySettingId(orgInsuranceSettings[i].Id);

                                    supplierEntities = supplierEntities.Where(t => t.SupplierId == input.SupplierId).ToList();

                                    for (int j = 0; j < supplierEntities.Count; j++)
                                    {
                                        List<OrgInsuranceSupplierAreaEntity> orgInsuranceSupplierAreaEntities = await _areaRepository.GetAllByGetByExcludeSupplierId(supplierEntities[j].Id);

                                        List<OrgInsuranceSupplierAreaEntity> orgInsuranceSupplierAreaEntities1 = null;

                                        if (input.ProductAreaIds[w].CooperationScopeIsDeleted == 1)
                                        {
                                            orgInsuranceSupplierAreaEntities1 = orgInsuranceSupplierAreaEntities.Where(t => t.SourceOrgId == input.OrgId).ToList();
                                        }
                                        else if(input.ProductAreaIds[w].SupplierSignAreaIdList!=null && input.ProductAreaIds[w].SupplierSignAreaIdList.Count>0)
                                        {
                                            orgInsuranceSupplierAreaEntities1 = orgInsuranceSupplierAreaEntities.Where(t => t.SourceOrgId == input.OrgId && input.ProductAreaIds[w].SupplierSignAreaIdList.Contains(t.AreaId)).ToList();
                                        }
                                        if (orgInsuranceSupplierAreaEntities.Count == orgInsuranceSupplierAreaEntities1.Count)
                                        {
                                            if (orgInsuranceSupplierAreaEntities.Count == 0 && supplierEntities[j].IsExcludeSupplier)
                                            {

                                            }
                                            else
                                            {
                                                SupplierDelEntity.Add(supplierEntities[j]);
                                            }                                            
                                        }
                                        AreaDelEntity.AddRange(orgInsuranceSupplierAreaEntities1);
                                        if (input.IsClearTW)
                                        {
                                            AreaDelEntity.AddRange(orgInsuranceSupplierAreaEntities.Where(t => t.SourceOrgId == input.OrgId && t.AreaId == 46245));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                if (AreaDelEntity.Count>0)
                {
                    await _areaRepository.BatchDelOrgInsuranceSupplierAreas(AreaDelEntity);
                }
                if (SupplierDelEntity.Count>0)
                {
                    await _repository.BatchDelOrgInsuranceExcludes(SupplierDelEntity);
                }
                return ResultDto.Success("Ok");
            }
            catch (Exception ex)
            {
                return ResultDto.Error(ex.Message);
            }
        }
    }
}